//
//  UIImageExt.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/11/5.
//

import Foundation
import SwiftUI

extension UIImage {
   func resizeImage(targetSize: CGSize) -> UIImage? {
      let size = self.size

      let widthRatio = targetSize.width / size.width
      let heightRatio = targetSize.height / size.height

      // Figure out what our orientation is, and use that to form the rectangle
      var newSize: CGSize
      if widthRatio > heightRatio {
         newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
      } else {
         newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
      }

      // This is the rect that we've calculated out and this is what is actually used below
      let rect = CGRect(origin: .zero, size: newSize)

      // Actually do the resizing to the rect using the ImageContext stuff
      UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
      self.draw(in: rect)
      let newImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()

      return newImage
   }

   func getOptiImage() -> UIImage? {
      let size = self.size
      var newSize = size
      if size.width >= 1280 {
         newSize.width = 1280
         newSize.height = size.height * newSize.width / size.width
      }
      return self.resizeImage(targetSize: newSize)
   }

   func rotated(byDegrees degrees: CGFloat) -> UIImage? {
      let radians = degrees * .pi / 180.0
      let rotatedSize = CGRect(origin: .zero, size: size)
         .applying(CGAffineTransform(rotationAngle: radians))
         .integral.size
      UIGraphicsBeginImageContext(rotatedSize)
      if let context = UIGraphicsGetCurrentContext() {
         context.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
         context.rotate(by: radians)
         draw(in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
         if let rotatedImage = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            return rotatedImage
         }
         UIGraphicsEndImageContext()
      }
      return nil
   }
}
